const Router = require('koa-router')
const {TokenValidator, NotEmptyValidate} = require('../../validators/validator')
const {LoginType}= require('../../lib/enum')
const {User} = require('../../models/user')
const {generateToken} = require('../../../core/util')
const {WXManager} = require('../../services/wx')
const {Auth} = require('../../../middlewares/auth')

// 专门用来产生token令牌的
const router = new Router({
  prefix: '/v1/token'
})

router.post('/', async(ctx, next) => {
  const v = await new TokenValidator().validate(ctx)
  // api  权限  公开api
  // token过期 或者不合法
  let token;
  switch(parseInt(v.get('body.type'))) {
    case LoginType.USER_MINI_PROGRAM: 
      token = await WXManager.codeToToken(v.get('body.account'))
      break;
    case LoginType.USER_EMAIL: 
      token = await emailLogin(v.get('body.account'), v.get('body.secret'))
      break;
    case LoginType.USER_MOBILE: 
     
      break;
    case LoginType.ADMIN_EMAIL: 

      break;
    default:
      throw new global.errs.ParameterException('没有相应的处理函数')
  }
  ctx.body = {token}
})

router.post('/verify', async(ctx, next) => {
  const v = await new NotEmptyValidate().validate(ctx)
  const result = Auth.verifyToken(v.get('body.token'))
  ctx.body = {
    is_valid: result
  }
})

async function emailLogin (account, secret) {
  const user = await User.verifyEmailPassword(account, secret)
  console.log('----user--')
  console.log(user)
  // return token = generateToken(user.id, 2)
  return token = generateToken(user.id, Auth.USER)
}
module.exports= router